package org.benjamin.lending.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.benjamin.lending.domain.BJUIUpload;
import org.benjamin.lending.domain.entity.*;
import org.benjamin.lending.repository.BorrowInfoRepository;
import org.benjamin.lending.repository.BorrowTenderRepository;
import org.benjamin.lending.repository.MemberMoneyLogRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by xywen on 2017/5/29.
 */
@Controller
@RequestMapping(value = "input")
public class InputController {

    private final Logger logger = LogManager.getLogger();

    @Autowired
    private MemberMoneyLogRepository memberMoneyLogRepository;

    @Autowired
    private BorrowTenderRepository borrowTenderRepository;

    @Autowired
    private BorrowInfoRepository borrowInfoRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DataSource dataSource;

    @GetMapping("toMemberInfo")
    public String inputMemberInfo() throws IOException {

        return "input/memberInfo";
    }

    @ResponseBody
    @PostMapping("doMemberInfo")
    public BJUIUpload doMemberInfoData(@RequestParam("fileObject") MultipartFile fileObject) throws IOException {
        logger.info("文件导入数据");
        BJUIUpload bjuiUpload = new BJUIUpload();
        bjuiUpload.setStatusCode(200);
        try {
            if (!fileObject.isEmpty()) {
                JsonNode resources = new ObjectMapper().readTree(fileObject.getInputStream());
                logger.info(fileObject.getOriginalFilename());
                if (fileObject.getOriginalFilename().contains("user_money_log")) {
                    logger.info("资金记录导入");
                    JsonNode jsonNode = resources.get("RECORDS");
                    List<MemberMoneyLog> memberMoneyLogs = new ArrayList<>();
                    Iterator<JsonNode> jsonNodes = jsonNode.iterator();
                    while (jsonNodes.hasNext()) {
                        JsonNode userMoneyLog = jsonNodes.next();
                        MemberMoneyLog memberMoneyLog = new MemberMoneyLog();
                        memberMoneyLog.setId(userMoneyLog.get("id").asInt());
                        memberMoneyLog.setInfo(userMoneyLog.get("info").asText());
                        memberMoneyLog.setAffectMoney(new BigDecimal(userMoneyLog.get("affect_money").asText()));
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
                        long createTime = simpleDateFormat.parse(userMoneyLog.get("create_at").asText()).getTime();
                        memberMoneyLog.setAddTime(new Timestamp(createTime));
                        memberMoneyLog.setType(userMoneyLog.get("type").asText());
                        memberMoneyLog.setAccountMoney(new BigDecimal(userMoneyLog.get("balance_money").asText()));
                        memberMoneyLog.setFreezeMoney(new BigDecimal(userMoneyLog.get("freeze_money").asText()));
                        memberMoneyLog.setCollectMoney(new BigDecimal(userMoneyLog.get("collect_money").asText()));
                        MemberInfo memberInfo = new MemberInfo();
                        memberInfo.setId(userMoneyLog.get("uid").asInt());
                        memberMoneyLog.setMemberInfo(memberInfo);

                        memberMoneyLogs.add(memberMoneyLog);
                    }
                    logger.info("资金记录导入数量是：{}", memberMoneyLogs.size());
                    this.memberMoneyLogRepository.save(memberMoneyLogs);
                    logger.info("资金记录导入完毕");
                }
                if (fileObject.getOriginalFilename().contains("borrow_investor")) {
                    logger.info("投资记录");
                    JsonNode jsonNode = resources.get("RECORDS");
//                    List<BorrowTender> borrowTenderList = new ArrayList<>();
                    NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(this.dataSource);
//                    SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(this.dataSource);
//                    simpleJdbcInsert = simpleJdbcInsert.withTableName("tab_borrow_tender");
//                    simpleJdbcInsert = simpleJdbcInsert.usingColumns("id","auto","uid","bid","investor_capital","investor_interest",
//                            "status","create_time","source","receive_capital","receive_interest");
                    List list = new ArrayList();
                    MapSqlParameterSource copy = new MapSqlParameterSource();
                    try{
                        for (JsonNode borrowInvestor : jsonNode) {
//                        Object[] inserts = new Object[]{borrowInvestor.get("id").asInt(), borrowInvestor.get("auto").asInt(), borrowInvestor.get("uid").asInt(),
//                                borrowInvestor.get("bid").asInt(), borrowInvestor.get("receive_capital").asDouble(), borrowInvestor.get("receive_interest").asDouble(),
//                                borrowInvestor.get("status").asText(), borrowInvestor.get("create_at").asText()};
//                        this.jdbcTemplate.update(
//                                "INSERT INTO tab_borrow_tender (id,auto,uid,bid,investor_capital,investor_interest,status,create_time) VALUES (?,?,?,?,?,?,?,?)",
//                                inserts);

                            MapSqlParameterSource parameterSource = new MapSqlParameterSource();
                            parameterSource.addValue("id", borrowInvestor.get("id").asLong());
                            parameterSource.addValue("auto", borrowInvestor.get("auto").asInt());
                            parameterSource.addValue("uid", borrowInvestor.get("uid").asInt());
                            parameterSource.addValue("bid", borrowInvestor.get("bid").asInt());
                            parameterSource.addValue("investor_capital", borrowInvestor.get("investor_capital").asDouble());
                            parameterSource.addValue("investor_interest", borrowInvestor.get("investor_interest").asDouble());
                            parameterSource.addValue("receive_capital", borrowInvestor.get("receive_capital").asDouble());
                            parameterSource.addValue("receive_interest", borrowInvestor.get("receive_interest").asDouble());
                            parameterSource.addValue("source", borrowInvestor.get("source").asInt());
                            parameterSource.addValue("status", borrowInvestor.get("status").asText());
                            parameterSource.addValue("create_time", borrowInvestor.get("create_at").asText());
                            //namedParameterJdbcTemplate.update("INSERT INTO tab_borrow_tender",parameters);
                            copy = parameterSource;
                            //simpleJdbcInsert.execute(parameterSource);
                            String sql = "INSERT INTO tab_borrow_tender (id,bid,uid,auto,status,investor_capital," +
                                    "investor_interest,receive_capital,receive_interest,source,create_time) " +
                                    "VALUES (:id,:bid,:uid,:auto,:status,:investor_capital,:investor_interest,:receive_capital,:receive_interest,:source,:create_time)";
                            namedParameterJdbcTemplate.update(sql,parameterSource);
                            //list.add(parameters);
                        }
                        Map<String,Object>[] parametersArray = new HashMap[list.size()];
                        list.toArray(parametersArray);

                    }catch(Exception e){
                        logger.error(e.getMessage(),e);
                        logger.info(copy.toString());
                        //logger.error(parameters.toString());
                    }
                    //this.borrowTenderRepository.save(borrowTenderList);
                    logger.info("投资记录导入完毕");

                } else if (fileObject.getOriginalFilename().contains("borrow")) {
                    logger.info("借款标记录");
                    JsonNode jsonNode = resources.get("RECORDS");
                    for (JsonNode borrow : jsonNode) {
                        Object[] inserts = new Object[]{borrow.get("id").asInt(), borrow.get("no").asText(), borrow.get("name").asText(),
                                borrow.get("rate").asDouble(), borrow.get("duration").asDouble(), borrow.get("total_money").asDouble(),
                                borrow.get("invest_money").asDouble(), PaymentMethod.transform(borrow.get("repayment_method").asText()).toString(),
                                BorrowStatus.valueOf(borrow.get("status").asText()).toString(), borrow.get("create_at").asText()};
                        this.jdbcTemplate.update(
                                "INSERT INTO tab_borrow_info (id,no,name,invest_rate,period,total_money,invest_money,payment_method," +
                                        "status,create_time)" +
                                        " VALUES (?,?,?,?,?,?,?,?,?,?)", inserts);
                    }
                    logger.info("借款标记录导入完毕");
                }
                //logger.info(resources);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return bjuiUpload;
    }
}
